import os
import matplotlib.pyplot as plt
import numpy as np
import json
import pandas as pd

dirRoot = '../Info/avgRes/'

if not os.path.exists(dirRoot + '/figure'):
    os.mkdir(dirRoot + '/figure')

contentList = dirRoot + 'contentList.txt'
delayInfo = dirRoot + 'delayInfo.txt'
hitRate = dirRoot + 'hitRate.txt'
hitRateList = dirRoot + 'hitRateList.txt'
intervalInfo = dirRoot + 'intervalInfo.txt'
stallInfo = dirRoot + 'stallTimeList.txt'
qualityFreqInfo = dirRoot + 'qualityFreq.txt'


# 顺序为 allCache noCache smartCache
def plotQualityFreq():
    with open(qualityFreqInfo) as f:
        content = f.readlines()

    cacheList = ['allCache', 'noCache', 'smartCache']

    content = [json.loads(each) for each in content]
    print(content)
    allCacheFreq = content[0]
    noCacheFreq = content[1]
    smartCacheFreq = content[2]

    qualityNum = len(allCacheFreq)

    x = np.arange(len(cacheList))
    width = 0.2

    qualityLabel = ['Lowest', 'Low', 'High', 'Highest']

    plt.bar(x - width, allCacheFreq, width=width, label=qualityLabel[1], color='#99CCFF')
    plt.bar(x, noCacheFreq, width=width, label=qualityLabel[2], color='#FFFF66')
    plt.bar(x + width, smartCacheFreq, width=width, label=qualityLabel[3], color='#666666')

    plt.xticks(x, labels=cacheList)
    plt.xlabel('Cache Strategy')
    plt.ylabel('Frequency')

    plt.title('Occurrence of Different Qualities')

    fontSize = 10
    for a, b in zip(x - width, allCacheFreq):
        plt.text(a, b, '%d' % b, va='bottom', ha='center', fontsize=fontSize)
    for a, b in zip(x, noCacheFreq):
        plt.text(a, b, '%d' % b, va='bottom', ha='center', fontsize=fontSize)
    for a, b in zip(x + width, smartCacheFreq):
        plt.text(a, b, '%d' % b, va='bottom', ha='center', fontsize=fontSize)

    plt.legend()
    plt.savefig(dirRoot + 'figure/qualityFreq.jpg', dpi=300)
    # plt.show()


def plotContent():
    plt.figure(figsize=(10, 5))
    with open(contentList) as f:
        lines = f.readlines()
    record = []
    total = []
    for line in lines:
        line = json.loads(line)
        record.append(line['sizeRecord'])
        total.append(line['totalSize'])
    # print(record, total)
    requestNum = [x + 1 for x in range(len(record[0]))]
    # print(requestNum)
    alpha = 0.6
    plt.fill(requestNum, record[0], label='allCache', color='red', alpha=alpha)
    plt.fill(requestNum, record[1], label='noCache', color='green', alpha=alpha)
    plt.fill(requestNum, record[2], label='smartCache', color='blue', alpha=alpha)
    plt.fill(requestNum, record[3], label='greedyCache', color='pink', alpha=alpha)

    plt.xticks(np.arange(0, len(requestNum), len(requestNum) / 10))  # 设置横坐标轴的刻度为 0 到 10 的数组
    plt.ylabel('Content Size')  # 横坐标轴的标题
    plt.xlabel('Request Sequence')  # 纵坐标轴的标题
    # plt.ylim([0, 1])  # 设置纵坐标轴范围为 0 到 2
    plt.legend()  # 显示图例, 图例中内容由 label 定义
    plt.grid()  # 显示网格
    plt.title('Content Size in MB')  # 图形的标题

    plt.savefig(dirRoot + 'figure/content.jpg', dpi=300)
    plt.show()


def plotDelay():
    plt.rc('font', family='Times New Roman')
    plt.rcParams['figure.figsize'] = (10, 7)
    plt.tick_params(labelsize=500)
    with open(delayInfo) as f:
        lines = f.readlines()
    totalResDelay = []
    avgResDelay = []
    totalTransDelay = []
    avgTransDelay = []
    for line in lines:
        line = json.loads(line)
        totalResDelay.append(line['totalResDelay'])
        avgResDelay.append(line['avgResDelay'])
        totalTransDelay.append(line['totalTransDelay'])
        avgTransDelay.append(line['avgTransDelay'])

    cacheList = ['randomCache','greedyCache','ROI-based Cache']

    x = np.arange(len(cacheList))
    width = 0.2

    fig, ax1 = plt.subplots()

    b1 = ax1.bar(x - 1.5 * width, totalResDelay, width=width, label='totalResDelay', color='#66CCCC')
    b2 = ax1.bar(x + 0.5 * width, totalTransDelay, width=width, label='totalTransDelay', color='#CCFF66')
    # 分轴表示 avg/total
    ax2 = ax1.twinx()
    b3 = ax2.bar(x - 0.5 * width, avgResDelay, width=width, label='avgResDelay', color='#FF99CC')
    b4 = ax2.bar(x + 1.5 * width, avgTransDelay, width=width, label='avgTransDelay', color='#666699')
    ax1.tick_params(axis='x', labelsize=20)
    ax1.tick_params(axis='y', labelsize=20)
    ax2.tick_params(axis='x', labelsize=20)
    ax2.tick_params(axis='y', labelsize=20)
    fontsize = 12
    for a, b in zip(x - 1.5 * width, totalResDelay):  # 柱子上的数字显示
        ax1.text(a, b, '%.2f' % b, ha='center', va='bottom', fontsize=fontsize)
    for a, b in zip(x - 0.5 * width, avgResDelay):
        ax2.text(a, b, '%.2f' % b, ha='center', va='bottom', fontsize=fontsize)
    for a, b in zip(x + 0.5 * width, totalTransDelay):
        ax1.text(a, b, '%.2f' % b, ha='center', va='bottom', fontsize=fontsize)
    for a, b in zip(x + 1.5 * width, avgTransDelay):
        ax2.text(a, b, '%.2f' % b, ha='center', va='bottom', fontsize=fontsize)
    plt.xticks(x, labels=cacheList, fontsize=500)

    ax1.set_xlabel('Cache Strategy', fontsize=30)

    ax1.set_ylabel('Delay Info (total) in s', fontsize=30)
    ax2.set_ylabel('Delay Info (avg) in s', fontsize=30)
    plt.legend(handles=[b1, b2, b3, b4], fontsize=20)



    # plt.title('Delay Info')
    plt.savefig(dirRoot + 'figure/delayInfo.jpg', dpi=300)
    plt.show()


def plotInterval():
    plt.figure(figsize=(10, 5))
    plt.rc('font', family='Times New Roman')
    info = []
    with open(intervalInfo) as f:
        for each in f.readlines():
            each = each.strip('\n')
            each = each[1:-1].split(',')
            info.append(each)
            # print(each)

    # noCacheInterval = [int(x) for x in info[0]]
    greedyCacheInterval = [int(x) for x in info[0]]
    divCacheInterval = [int(x) for x in info[1]]
    evalCacheInterval = [int(x) for x in info[2]]

    # requestNum = [x + 1 for x in range(len(noCacheInterval))]
    data = greedyCacheInterval
    denominator = len(data)  # 分母数量
    Data = pd.Series(data)  # 将数据转换为Series利用分组频数计算
    Fre = Data.value_counts()
    Fre_sort = Fre.sort_index(axis=0, ascending=True)
    Fre_df = Fre_sort.reset_index()  # 将Series数据转换为DataFrame
    Fre_df[0] = Fre_df[0] / denominator  # 转换成概率
    Fre_df.columns = ['Rds', 'Fre']
    Fre_df['cumsum'] = np.cumsum(Fre_df['Fre'])

    data1 = divCacheInterval
    denominator1 = len(data1)  # 分母数量
    Data1 = pd.Series(data1)  # 将数据转换为Series利用分组频数计算
    Fre1 = Data1.value_counts()
    Fre_sort1 = Fre1.sort_index(axis=0, ascending=True)
    Fre_df1 = Fre_sort1.reset_index()  # 将Series数据转换为DataFrame
    Fre_df1[0] = Fre_df1[0] / denominator1  # 转换成概率
    Fre_df1.columns = ['Rds', 'Fre']
    Fre_df1['cumsum'] = np.cumsum(Fre_df1['Fre'])

    data2 = evalCacheInterval
    denominator2 = len(data2)  # 分母数量
    Data2 = pd.Series(data2)  # 将数据转换为Series利用分组频数计算
    Fre2 = Data2.value_counts()
    Fre_sort2 = Fre2.sort_index(axis=0, ascending=True)
    Fre_df2 = Fre_sort2.reset_index()  # 将Series数据转换为DataFrame
    Fre_df2[0] = Fre_df2[0] / denominator2  # 转换成概率
    Fre_df2.columns = ['Rds', 'Fre']
    Fre_df2['cumsum'] = np.cumsum(Fre_df2['Fre'])

    plot = plt.figure()
    ax1 = plot.add_subplot(1, 1, 1)
    ax1.plot(Fre_df['Rds'], Fre_df['cumsum'], '--')
    ax1.plot(Fre_df1['Rds'], Fre_df1['cumsum'],'--')
    ax1.plot(Fre_df2['Rds'], Fre_df2['cumsum'],  '-')
    ax1.tick_params(axis='x', labelsize=20)
    ax1.tick_params(axis='y', labelsize=20)
    ax1.set_xlabel("avgResDelay(ms)",fontsize=30)
    ax1.set_ylabel("CDF", fontsize=30)
    ax1.set_xlim(0, 200)


    plt.legend(["randomCache","greedyCache","ROI-based Cache"],loc=4, fontsize=15)
    plt.savefig(dirRoot + 'figure/interval.jpg', dpi=300) 
    plt.show()

    # plt.ylim([0, 1500])
    #
    # alpha = 0.9
    # # plt.fill(requestNum, allCacheInterval, label='noCache', color='blue', alpha=0.2)
    # plt.fill(requestNum, greedyCacheInterval, label='greedyCache', color='black', alpha=0.6)
    # plt.fill(requestNum, divCacheInterval, label='ROI-based 1', color='yellow', alpha=0.8)
    # plt.fill(requestNum, evalCacheInterval, label='ROI-based 2', color='pink', alpha=0.6)
    #
    # plt.title('Request Interval Info')
    # # plt.yticks(np.arange(0,10000,1000))
    # plt.xlabel('Request Sequence')
    # plt.ylabel('Request Interval /ms')
    # plt.grid()
    #
    # plt.legend()
    # plt.savefig(dirRoot + 'figure/interval.jpg', dpi=300)
    # plt.show()


def plotHitRate_StallTime():
    # plt.figure(figsize=(10, 5))
    with open(hitRate) as f:
        ratio = [float(x.strip('\n')) for x in f.readlines()]
    print(ratio)

    with open(stallInfo) as f:
        stall = [float(x.strip('\n')) for x in f.readlines()]
    cacheList = ['noCache', 'greedyCache', 'ROI-based 1', 'ROI-based 2']
    x = np.arange(len(cacheList))
    width = 0.3

    fig, ax1 = plt.subplots()

    b1 = ax1.bar(x - 0.5 * width, ratio, width=width, label='Hit Ratio', color='#993333')
    ax2 = ax1.twinx()
    b2 = ax2.bar(x + 0.5 * width, stall, width=width, label='Stall Time', color='#CC9966')

    ax1.set_ylabel('Hit Ratio', fontsize=15)
    ax2.set_ylabel('Stall Time /s', fontsize=15)

    # ax1.ylim(0, 1)

    ax1.set_xlabel('Cache Strategy', fontsize=15)
    plt.xticks(x, labels=cacheList, fontsize=15)

    for a, b in zip(x, ratio):
        ax1.text(a - 0.5 * width, b, '%.2f' % b, ha='center', va='bottom', fontsize=8)
    for a, b in zip(x, stall):
        ax2.text(a + 0.5 * width, b, '%.2f' % b, ha='center', va='bottom', fontsize=8)

    plt.title('HitRatio & StallTime', fontsize=15)
    plt.legend(handles=[b1, b2])
    plt.savefig(dirRoot + 'figure/hitStall.jpg', dpi=300)
    plt.show()


def plotHitRateList():
    plt.figure(figsize=(15, 5))
    ifHitList = []
    with open(hitRateList) as f:
        for each in f.readlines():
            each = each.strip('\n')
            each = each[1:-1].split(',')
            each = [int(x) for x in each]
            ifHitList.append(each)
    # print(ifHitList)

    requests = [x + 1 for x in range(len(ifHitList[0]))]

    ratio1 = round(ifHitList[0].count(1) / len(ifHitList[0]), 2)
    ratio2 = round(ifHitList[1].count(1) / len(ifHitList[1]), 2)
    ratio3 = round(ifHitList[2].count(1) / len(ifHitList[2]), 2)
    ratio4 = round(ifHitList[3].count(1) / len(ifHitList[3]), 2)

    plt.scatter(requests, ifHitList[0], label='allCache ' + str(ratio1), c='black', s=100)
    plt.scatter(requests, ifHitList[1], label='noCache ' + str(ratio2), c='gray', s=100)
    plt.scatter(requests, ifHitList[2], label='smartCache ' + str(ratio3), c='red', s=0.2)
    plt.scatter(requests, ifHitList[3], label='greedyCache ' + str(ratio4), c='yellow', s=0.2)

    # plt.fill_between(requests, ifHitList[2], color='green', alpha=.5)

    yLabels = ['Miss', 'Hit']
    plt.yticks([0, 1], labels=yLabels)

    plt.xticks(np.arange(0, len(requests) + len(requests) / 10, len(requests) / 10))
    plt.xlabel('Request Sequence')
    plt.ylabel('Hit or Miss')
    plt.title('Hit/Miss Record')

    plt.legend(title='cache strategy')
    plt.savefig(dirRoot + 'figure/hitRecord.jpg', dpi=300)

    plt.show()


# plotContent()
plotDelay()
plotInterval()
# plotHitRate_StallTime()
# plotHitRateList()


# plotQualityFreq()
